package org.lex.ftplist.util;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import org.apache.commons.net.ftp.FTPFile;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

public class Xmls {
    // xml element name

    public static final String FTPList = "FTPList";
    public static final String Node = "Node";
    public static final String name = "name";
    public static final String id = "id";
    public static final String parentId = "parentId";
    public static final String date = "date";
    public static final String Index = "Index";
    public static final String FTP = "FTP";
    public static final String User = "User";
    public static final String Password = "Password";
    public static final String Host = "Host";
    public static final String Port = "Port";
    public static final String Path = "Path";

    public static Element encodeFtpFile(FTPFile file) {
        Element e = DocumentHelper.createElement(Node);
        List<Pair<String, String>> attrs = getProperties(file);
        for (Pair<String, String> a : attrs) {
            if (null != a.first() && null != a.second()) {
                e.addAttribute(a.first(), a.second());
            }
        }
        return e;
    }

    public static FTPFile decodeFtpFile(Element e) {
        FTPFile file = new FTPFile();
        file.setType(Integer.parseInt(e.attributeValue("type")));
        file.setHardLinkCount(Integer.parseInt(e.attributeValue("hardLinkCount")));
        file.setSize(Long.parseLong(e.attributeValue("size")));
        file.setRawListing(e.attributeValue("rawListing"));
        file.setUser(e.attributeValue("user"));
        file.setGroup(e.attributeValue("group"));
        file.setName(e.attributeValue("name"));
        file.setLink(e.attributeValue("link"));
        Calendar calc = Calendar.getInstance();
        calc.setTimeInMillis(Long.parseLong(e.attributeValue("date")));
        file.setTimestamp(calc);
        return file;
    }

    private static List<Pair<String, String>> getProperties(FTPFile file) {
        List<Pair<String, String>> list = new ArrayList<Pair<String, String>>();
        list.add(Pair.valueOf("type", Integer.toString(file.getType())));
        list.add(Pair.valueOf("hardLinkCount", Integer.toString(file.getHardLinkCount())));
        list.add(Pair.valueOf("size", Long.toString(file.getSize())));
        list.add(Pair.valueOf("rawListing", file.getRawListing()));
        list.add(Pair.valueOf("user", file.getUser()));
        list.add(Pair.valueOf("group", file.getGroup()));
        list.add(Pair.valueOf("name", file.getName()));
        list.add(Pair.valueOf("link", file.getLink()));
        String dateStr = "0";
        if (null != file.getTimestamp()) {
            dateStr = Long.toString(file.getTimestamp().getTimeInMillis());
        }
        list.add(Pair.valueOf("date", dateStr));
        return list;
    }
}
